package summer.codegenerator.web;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import summer.codegenerator.dto.Result;
import summer.codegenerator.common.exception.ExceptionCode;

/**
 * 异常处理和返回值包装统一处理地点
 * 
 * @author 蒋振
 * @creation 2019年6月18日 下午1:04:33
 */
@ControllerAdvice
@ResponseBody
public class ResponseWrapperController implements ResponseBodyAdvice<Object> {

	private String getExceptionCode(Exception e) {
		String code = StringUtils.capitalize(e.getClass().getSimpleName());
		// "XXXEXCEPTION" -> "XXX"
		return code.substring(0, code.length() - 9);
	}

	@ExceptionHandler({ Exception.class })
	public Result exceptionHandler(Exception e) {
		e.printStackTrace();
		Result result = new Result();
		result.setCode("ERROR");
		result.setData(getExceptionCode(e));
		return result;
	}

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		Object result;
		if (body == null) {
			result = new Result();
		} else if (body instanceof File) {
			result = body;
		} else if (body instanceof Result || body instanceof Result) {
			result = body;
		} else {
			Result cr = new Result();
			cr.setData(body);
			result = cr;
		}
		return result;
	}
}
